use configparser::ini::Ini;
use rand::distr::Alphanumeric;
use rand::prelude::ThreadRng;
use rand::Rng;
use std::path::PathBuf;
use tracing::{error, info};

///
/// 获取当前电脑的设备码
///
/// result -> 返回一个32位的随机码
///
pub fn get_device_code() -> anyhow::Result<String> {
    info!("从config.ini获取设备识别code码.");
    // 获取当前目录下是否存在config.ini
    let local_path = std::env::current_dir()?;
    let config_path = PathBuf::from(&local_path).join(r"config.ini");
    let mut device_code = String::new();
    // 没有则生产并记录
    if !config_path.exists() {
        error!("获取设备识别码失败，重新生成配置文件和识别码.");
        device_code = generate_device_code(config_path.to_str().unwrap())?;
    }else {
        // 存在则获取配置device键值对
        let mut config = Ini::new();
        config.load(&config_path).unwrap();
        match config.get("device","code") {
            Some(code) => device_code = code.to_string(),
            None => {
                println!("No device code found in config");
                device_code = generate_device_code(config_path.to_str().unwrap())?;
            }
        } ;
    }
    info!("设备识别码为: {}", device_code);
    Ok(device_code)
}

///
/// 生产随机🐎
///
fn generate_device_code(path: &str) -> anyhow::Result<String> {
    let mut rng = ThreadRng::default();
    let device_code_random: String = (0..32)
        .map(|_| rng.sample(Alphanumeric) as char)
        .collect();

    let mut config = Ini::new();
    config.set("device","code", Some(device_code_random.clone()));
    config.write(&path)?;
    Ok(device_code_random)
}